/*mytop命令*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

/*进程信息结构体*/
struct ProcessInfo
{
    int pid;
    char *user;
    int priority;
    int nice;
    long *virt_memory;
    long *res_memory;
    long *shr_memory;
    char state;
    float cpu_usage;
    float mem_usage;
    char *time;
    char *command;
    struct ProcessInfo *next;
};

/*进程信息查询函数*/
/*zl*/
int getProcesspid(struct ProcessInfo **process)
{
    // 获取进程列表
    DIR *procdir = opendir("/proc");
    if (procdir == NULL) {
        perror("Failed to open /proc directory");
        exit(1);
    }
    struct dirent *entry;
    while ((entry = readdir(procdir)) != NULL) {
        char path[512];
        snprintf(path, sizeof(path), "/proc/%s", entry->d_name);
        struct stat statbuf;

        if (stat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
            // 如果路径对应的是一个目录，则可以认为是进程目录
            int pid = atoi(entry->d_name);
            if (pid > 0) {
                // 分配内存来存储新的进程信息
                struct ProcessInfo *newProcess = (struct ProcessInfo *)malloc(sizeof(struct ProcessInfo));
                memset(newProcess, 0, sizeof(struct ProcessInfo)); // 初始化结构体为0
                newProcess->pid = pid;
                // 将新的进程信息添加到链表中
                newProcess->next = NULL;
                if (*process == NULL) {
                    *process = newProcess;
                    } else {
                        // 找到链表的尾部
                        struct ProcessInfo *tail = *process;
                        while (tail->next != NULL)
                         {
                            tail = tail->next;
                         }
                         tail->next = newProcess;
                 }
            }
        }
    }

    closedir(procdir);

}
/*wxy*/

/*fll*/

/*sc*/

/*ltj*/

/*打印*/
void Print(struct ProcessInfo **process)
{
    struct ProcessInfo *current = process;
    printf("进程PID 用户 优先级 Nice值 虚拟内存 常驻内存 共享内存 状态 CPU使用率 内存使用率 运行时间 命令\n");
    while (current != NULL)
    {
        printf("%d ", current->pid);
        // printf("%s ", current->user);
        // printf("%d ", current->priority);
        // printf("%d ", current->nice);
        // printf("%ld ", current->virt_memory);
        // printf("%ld ", current->res_memory);
        // printf("%ld ", current->shr_memory);
        // printf("%c ", current->state);
        // printf("%.2f%% ", current->cpu_usage);
        // printf("%.2f%% ", current->mem_usage);
        // printf("%s ", current->time);
        // printf("%s ", current->command);
        printf("\n");

        current = current->next;
    }
}

/*main函数*/
int main()
{
    struct ProcessInfo *process = NULL;
    getProcesspid(&process);

    
    /*打印*/
    Print(process);
    // 释放分配的内存
    struct ProcessInfo *current = process;
    while (current != NULL)
    {
        struct ProcessInfo *temp = current;
        current = current->next;
        free(temp);
    }
    return 0;
}